//
//  CustomPresentationSecondViewController.swift
//  CustomTransitions
//
//  Created by fuyoufang on 2021/10/12.
//

import UIKit


class CustomPresentationSecondViewController: BaseSecondViewController {
    
    // MARK: UI
    lazy var slider = UISlider().then {
        $0.addTarget(self, action: #selector(sliderValueChange(slider:)), for: .valueChanged)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupSubviews()
        updatePreferredContentSize(traitCollection: self.traitCollection)
    }
    
    func setupSubviews() {
        nextStepButton.setTitle("Present With Custom Transition", for: .normal)
        tipLabel.font = UIFont.systemFont(ofSize: 60)
        view.addSubview(slider)
        slider.snp.makeConstraints {
            $0.left.equalTo(40)
            $0.right.equalTo(-40)
            $0.bottom.equalTo(nextStepButton.snp.top).offset(-20)
        }
        
        tipLabel.snp.remakeConstraints {
            $0.top.equalToSuperview()
            $0.bottom.equalTo(slider.snp.top)
            $0.centerX.equalToSuperview()
        }
    }
    
    override func willTransition(to newCollection: UITraitCollection,
                                 with coordinator: UIViewControllerTransitionCoordinator) {
        debugPrint("willTransition")
        super.willTransition(to: newCollection, with: coordinator)
        // 注意此处使用的是 newCollection
        updatePreferredContentSize(traitCollection: newCollection)
    }
    
    
    /// 此处的 size 为 UIPresentationController 中 size(forChildContentContainer container:, withParentContainerSize parentSize:) 方法返回的大小
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        debugPrint("viewWillTransition")
        super.viewWillTransition(to: size, with: coordinator)
        preferredContentSize = size
    }
    
    func updatePreferredContentSize(traitCollection: UITraitCollection) {
        preferredContentSize = CGSize(width: self.view.bounds.size.width,
                                           height: traitCollection.verticalSizeClass == .compact ? 270 : 420)
        
        slider.do {
            $0.minimumValue = 220
            $0.maximumValue = Float(preferredContentSize.height)
            $0.value = Float(preferredContentSize.height)
        }
    }
    
    
    override func nextStepAction(sender: Any) {
        let viewController = CustomPresentationThirdViewController()
            .then {
                $0.modalPresentationStyle = .fullScreen
            }
        present(viewController, animated: true, completion: nil)
    }
    
    @objc func sliderValueChange(slider: UISlider) {
        self.preferredContentSize = CGSize(width: self.view.bounds.size.width,
                                           height: CGFloat(slider.value))
    }
}
